<template>
  <div>
    <SearchForm @search="getTableData" @reset="clearSearchForm" :is-search-disabled="isSearchDisabled">
      <el-col :span="8" :xs="24" v-show="$permiss[816]">
        <el-form-item :label="$t('所属租户')">
          <el-select style="width: 100%" v-model="page.tenantId" clearable>
            <el-option v-for="item in tenantList" :key="item.adminUserId" :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户姓名')">
          <el-input v-model="page.userName"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('手机号码')">
          <el-input v-model="page.phone"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('身份证号码')" prop="phone" label-width="100px">
          <el-input v-model="page.idCard" clearable/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[817]">
        <el-form-item :label="$t('营销APP')">
          <el-select style="width: 100%" v-model="page.benefitApp" clearable>
            <el-option v-for="item in marketingProduct" :key="item.productId" :label="item.appName"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[819]">
        <el-form-item :label="$t('营销员')">
          <el-select style="width: 100%" v-model="page.adminUserId" clearable>
            <el-option v-for="item in marketPersonnel" :key="item.adminUserId" :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('营销状态')">
          <el-select style="width: 100%" v-model="page.status" clearable>
            <el-option v-for="item in marketingStatus" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('订单状态')">
          <el-select style="width: 100%" v-model="page.approvalResult" clearable>
            <el-option v-for="item in orderStatus" :key="item.key" :label="item.value"
                       :value="item.key"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('跟进次数')">
          <el-input v-model.number="page.followNum" class="input-with-select">
            <el-select style="width: 60px" v-model="page.followNumSymbol"
                       slot="prepend">
              <el-option v-for="item in symbolList" :key="item.label" :label="item.label"
                         :value="item.label"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[866]">
        <el-form-item :label="$t('营销结果')">
          <el-cascader
              style="width: 100%"
              v-model="page.causeKey"
              :options="selectCause"
              :props="{ checkStrictly: true,value:'key',label:'value' }"
              clearable></el-cascader>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('数据来源')">
          <el-select style="width: 100%" v-model="page.resourceApp" clearable>
            <el-option v-for="item in marketingProduct" :key="item.productId" :label="item.appName"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('IVR按键')">
          <el-select style="width: 100%" v-model="page.ivrResult" clearable>
            <el-option label="0" value="0"></el-option>
            <el-option label="1" value="1"></el-option>
            <el-option label="2" value="2"></el-option>
            <el-option label="3" value="3"></el-option>
            <el-option label="4" value="4"></el-option>
            <el-option label="5" value="5"></el-option>
            <el-option label="6" value="6"></el-option>
            <el-option label="7" value="7"></el-option>
            <el-option label="8" value="8"></el-option>
            <el-option label="9" value="9"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('IVR结果')">
          <el-select style="width: 100%" v-model="page.result" clearable>
            <el-option :label="$t('成功接通')" value="成功接通"></el-option>
            <el-option :label="$t('未接通')" value="未接通"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('注册时间')">
          <el-date-picker
              v-model="page.registerTimeValue"
              style="width: 100%"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('申请时间')">
          <el-date-picker
              v-model="page.applyTimeValue"
              style="width: 100%"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('结清时间')" label-width="100px">
          <el-date-picker
              v-model="page.settleTimeValue"
              style="width: 100%"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('分单时间')">
          <el-date-picker
              v-model="page.distributionTimeValue"
              style="width: 100%"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('跟进时间')">
          <el-date-picker
              v-model="page.followTimeValue"
              style="width: 100%"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>
    <el-card shadow="never" style="margin-top: 10px">
      <div style="text-align: right">
        <el-button type="primary" @click="visibleTransfer = true" v-show="$permiss[823]">{{ $t('调单') }}</el-button>
      </div>
      <Table style="margin-top: 10px" :table-column="tableColumn" @handleSizeChange="handleSizeChange"
             @handleCurrentChange="handleCurrentChange" :table-data="tableData" :page="page" :loading="loading">
        <template slot="auth" slot-scope="{row}">
          <AuthStatus :row="row"/>
        </template>
        <template slot="phone" slot-scope="{row}">
          <el-popover
              v-if="$permiss[1368]"
              placement="right"
              width="120px"
              trigger="click">
            <SelectCallPhone :phone="callPhoneNumber" :modeType="11" :userId="row.userId"/>
            <el-link slot="reference" @click="callPhone(row)" :underline="false" type="primary">{{
                row.phone
              }}
            </el-link>
          </el-popover>
          <div v-else>{{ row.phone }}</div>
        </template>
        <template slot="result" slot-scope="{row}">
          <div v-if="row.cause1 && row.cause1">
            {{ row.cause1 + '-' + row.cause2 }}
          </div>
        </template>
        <template slot="isBlack" slot-scope="{row}">
          {{ row.isBlackList === 0 ? $t('否') : row.isBlackList === 1 ? $t('是') : '' }}
        </template>
        <template slot="handle" slot-scope="{row}">
          <el-button v-show="$permiss[821]" type="text" @click="lookRemark(row)">{{ $t('备注详情') }}</el-button>
        </template>
      </Table>
    </el-card>
    <!--     调单-->
    <Dialog :visible.sync="visibleTransfer" :title="$t('调单')" width="85%" @close="clearTransfebOrder" :footer="false">
      <TransferOrder ref="transferOrder" :productList="marketingProduct" @confirm="getTableData"/>
    </Dialog>
    <!--    备注详情-->
    <Dialog :visible.sync="visibleRemark" :title="$t('备注详情')" :footer="false" @cancel="visibleRemark = false"
            @close="recordPage.timeValue = null" width="50%">
      <el-row :gutter="24" style="margin: 0">
        <el-form label-width="80px">
          <el-col :span="14">
            <el-form-item :label="$t('跟进时间')">
              <el-date-picker
                  v-model="recordPage.timeValue"
                  style="width: 100%"
                  unlink-panels
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="~"
                  :start-placeholder="$t('开始时间')"
                  :end-placeholder="$t('结束时间')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10" style="text-align: right">
            <el-button type="primary" @click="lookRemark(tableRows)">{{ $t('查询') }}</el-button>
            <el-button @click="recordPage.timeValue = [],lookRemark(tableRows)">{{ $t('重置') }}</el-button>
          </el-col>
        </el-form>
      </el-row>
      <Table :table-column="recordColumn" :table-data="recordData" :page="recordPage">
        <template slot="result" slot-scope="{row}">
          <div v-if="row.cause1 && row.cause1">
            {{ row.cause1 + '-' + row.cause2 }}
          </div>
        </template>
      </Table>
    </Dialog>
  </div>
</template>

<script>
import TransferOrder from './compoents/transferOrder'
import AuthStatus from '../../registerNotApply/authStatus'
import {dateFormatSection, defaultTimeDate} from "@/utils/tools";
import {selectProduct, selectTenant, selectMarketingStaff} from "@/api/system";
import {shareList, shareRemarksList, fetchMarketingCause, marketingCallPhone} from '@/api/marketing'

export default {
  name: "ShareUserMarketAllList",

  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        followNumSymbol: '≧',
        distributionTimeValue: defaultTimeDate(14)
      },
      tenantList: [],
      marketPersonnel: [],
      marketingProduct: [],
      resourcProduct: [],
      symbolList: [
        {label: '>'},
        {label: '='},
        {label: '≧'},
        {label: '≦'},
        {label: '<'}
      ],
      marketingStatus: [
        {label: this.$t('未注册'), value: 1},
        {label: this.$t('未申请'), value: 2},
        {label: this.$t('已申请'), value: 3},
      ],
      tableColumn: [
        {label: this.$t('用户姓名'), prop: 'userName', minWidth: 100},
        {label: this.$t('手机号码'), prop: 'phone', minWidth: 100, slot: 'phone'},
        {label: this.$t('邮箱'), prop: 'email', minWidth: 100},
        {label: 'whatsAPP', prop: 'whatsApp', minWidth: 100},
        {label: 'zalo', prop: 'zalo', minWidth: 100},
        {label: this.$t('身份证号码'), prop: 'idCard', minWidth: 100},
        {label: this.$t('是否黑名单'), slot: 'isBlack', minWidth: 100},
        {label: this.$t('性别'), prop: 'gender', minWidth: 100},
        {label: this.$t('年龄'), prop: 'age', minWidth: 100},
        // {label: this.$t('借款总金额'), prop: 'loanTotalAmount', minWidth: 100},
        // {label: this.$t('还款总金额'), prop: 'actualPayAmount', minWidth: 100},
        {label: this.$t('结清时间'), prop: 'lastSettleTime', minWidth: 150},
        {label: this.$t('分单时间'), prop: 'createTime', minWidth: 150},
        {label: this.$t('注册时间'), prop: 'registerTime', minWidth: 150},
        {label: this.$t('申请时间'), prop: 'loanTime', minWidth: 150},
        {label: this.$t('认证状态'), slot: 'auth', minWidth: 200},
        {label: this.$t('IVR按键'), prop: 'ivrResult', minWidth: 100},
        {label: this.$t('IVR结果'), prop: 'result', minWidth: 100},
        {label: this.$t('营销APP'), prop: 'benefitAppName', minWidth: 100},
        {label: this.$t('营销员'), prop: 'adminUserName', minWidth: 100},
        {label: this.$t('营销状态'), prop: 'status', minWidth: 100},
        {label: this.$t('营销结果'), slot: 'result', minWidth: 100},
        {label: this.$t('订单状态'), prop: 'approvalResult', minWidth: 100},
        {label: this.$t('跟进次数'), prop: 'followNum', minWidth: 100},
        {label: this.$t('跟进时间'), prop: 'followTime', minWidth: 150},
        {label: this.$t('数据来源'), prop: 'resourceAppName', minWidth: 100},
        {label: this.$t('所属租户'), prop: 'tenantName', minWidth: 100, isHide: !this.$permiss[816]},
        {label: this.$t('操作'), minWidth: 100, slot: 'handle', fixed: 'right', isHide: !this.$permiss[821]},
      ],
      tableData: [],
      visibleTransfer: false,
      visibleRemark: false,
      loading: false,
      recordColumn: [
        {label: this.$t('跟进时间'), prop: 'createTime', minWidth: 150},
        {label: this.$t('营销结果'), slot: 'result', minWidth: 100},
        {label: this.$t('备注'), prop: 'remark', minWidth: 200},
        {label: this.$t('处理人'), prop: 'adminUserName', minWidth: 100},
      ],
      orderStatus: [
        {key: -1, value: this.$t('已关闭'), color: '#5e5e5e'},
        {key: 0, value: this.$t("未分配"), color: '#1200ff'},
        {key: 1, value: this.$t("审核中"), color: "#6e00cd"},
        {key: 2, value: this.$t("拒绝"), color: "#f579df"},
        {key: 5, value: this.$t("待打款"), color: "#06d506"},
        {key: 6, value: this.$t("待还款"), color: "#ffc000"},
        {key: 8, value: this.$t("逾期"), color: "#ff0000"},
        {key: 9, value: this.$t("结清"), color: "#53aef3"},
      ],
      recordData: [],
      recordPage: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      tableRows: {},
      marketingCause: [],
      selectCause: [],
      isSearchDisabled: false,
      callPhoneNumber: null
    }
  },
  components: {
    TransferOrder,
    AuthStatus
  },
  mounted() {
    this.getSelect()
    this.getTableData()
  },
  methods: {
    async getTableData() {
      this.isSearchDisabled = true
      this.loading = true
      const [applyStartTime, applyEndTime] = dateFormatSection(this.page.applyTimeValue || [])
      const [lastSettleStartTime, lastSettleEndTime] = dateFormatSection(this.page.settleTimeValue || [])
      const [separateOrderStartTime, separateOrderEndTime] = dateFormatSection(this.page.distributionTimeValue || [])
      const [followStartTime, followEndTime] = dateFormatSection(this.page.followTimeValue || [])
      const [registerStartTime, registerEndTime] = dateFormatSection(this.page.registerTimeValue || [])
      const [cause1, cause2] = this.page.causeKey || []
      const params = {
        ...this.page,
        applyStartTime, applyEndTime, separateOrderStartTime, separateOrderEndTime, followStartTime, followEndTime,
        lastSettleStartTime, lastSettleEndTime,
        registerStartTime, registerEndTime,
        cause1, cause2,
        followNumSymbol: this.page.followNumSymbol === '≧' ? '>=' : this.page.followNumSymbol === '≦' ? '<=' : this.page.followNumSymbol,
      }

      delete params.applyTimeValue
      delete params.settleTimeValue
      delete params.distributionTimeValue
      delete params.followTimeValue
      delete params.registerTimeValue
      delete params.causeKey
      const res = await shareList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list.map(item => {
          const approvalResult = this.orderStatus.filter(v => v.key === parseInt(item.approvalResult))
          const status = this.marketingStatus.filter(v => v.value === parseInt(item.status))
          item.status = status.length ? status[0].label : ''
          item.result = this.$t(item.result || '')
          item.gender = item.gender === 1 ? this.$t('男') : item.gender === 0 ? this.$t('女') : ''
          item.approvalResult = approvalResult && approvalResult.length ? approvalResult[0].value : ''
          return item
        })
        this.page = {
          ...this.page,
          total
        }
        this.isSearchDisabled = false
        this.loading = false
      } else {
        this.loading = false
        this.isSearchDisabled = false
      }
    },
    clearTransfebOrder() {
      this.$refs.transferOrder.clearForm()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    clearSearchForm() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        followNumSymbol: '≧'
      }
      this.getTableData()
    },
    // 打电话
    async callPhone({userId}) {
      const res = await marketingCallPhone({userId: userId})
      if (res.code === 1) {
        this.callPhoneNumber = res.data.phone
      }
    },
    // 查看营销备注
    async lookRemark(row) {
      const [followTimeStart, followTimeEnd] = dateFormatSection(this.recordPage.timeValue || [])
      const params = {
        ...this.recordPage,
        followTimeStart, followTimeEnd,
        shareUserMarketId: row.id
      }
      delete params.timeValue
      this.tableRows = {...row}
      const res = await shareRemarksList(params)
      if (res.code === 1) {
        const {list, pageNum, pageSize, total} = res.data
        this.visibleRemark = true
        this.recordData = list
        this.recordPage = {
          ...this.recordPage,
          pageNum, pageSize, total
        }
      }
    },
    async getMarketPersonnel() {
      const res = await selectMarketingStaff({
        type: 2
      })
      if (res.code === 1) {
        this.marketPersonnel = res.data
      }
    },
    async getSelect() {
      selectTenant().then(res => {
        this.tenantList = res.data
      })
      selectProduct().then(res => {
        this.marketingProduct = res.data
      })
      this.$permiss[819] && this.getMarketPersonnel()
      fetchMarketingCause().then(res => {
        this.marketingCause = res.data
        const marketingCause = this.marketingCause.filter(item => {
          if (item.code === 0) {
            const children = this.marketingCause.filter(child => child.type === item.type && child.code !== 0)
            if (children.length > 0) item.children = children
            return item.code === 0
          }
        })
        this.selectCause = marketingCause
      })
    }
  }
}
</script>

<style scoped>

</style>
